package atguigu.excel;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ExportReportUtils {

    // 把文件放到一个临时的目录中
    public static final String TEMP_REPORT_DIR_JD = "jdJiancheJieguoReport";
    public static final String TEMP_REPORT_DIR_LY = "lyJianceJielunReport";
    public static final String TEMPLATE_TYPE_RECORD = "检测记录";
    public static final String TEMPLATE_TYPE_REPORT = "检测报告";

    /**
     * 将workbook写到指定文件夹下
     * @param workbook
     * @param realPath 绝对路径
     * @param fileName 文件名
     * @return
     * @throws Exception
     */
    public static File writeWorkbook2Local(XSSFWorkbook workbook,String realPath,String fileName) throws Exception {
        File realFilePath = new File(realPath);// file文件夹
        if(!realFilePath.exists()){ // 如果未创建则新建
            realFilePath.mkdirs();
        }
        // 本地的文件缓存清空一下
        String fileAbsPath = realFilePath.getAbsolutePath()+File.separator+fileName;
        File file = new File(fileAbsPath);
        FileOutputStream fileOut = FileUtils.openOutputStream(file);
        workbook.write(fileOut);
        fileOut.flush();
        fileOut.close();
        workbook.close();
        return file;
    }

    public static String dealWindowsUnlawfulTo$(String fileName) {
        Pattern pattern = Pattern.compile("[\\\\/:*?\"<>|]");
        Matcher matcher = pattern.matcher(fileName);
        String str = matcher.replaceAll(Matcher.quoteReplacement("$"));
        return str;
    }

    /**
     * 将多个Excel打包成zip文件
     * @param srcfile
     * @param zipfile
     */
    public static void zipFiles(List<File> srcfile, File zipfile) {
        byte[] buf = new byte[1024];
        try (ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile));){
            for (int i = 0; i < srcfile.size(); i++) {
                File file = srcfile.get(i);
                try(FileInputStream in = new FileInputStream(file);){
                    out.putNextEntry(new ZipEntry(file.getName()));
                    int len;
                    while ((len = in.read(buf)) > 0) {
                        out.write(buf, 0, len);
                    }
                    out.closeEntry();
                }catch(FileNotFoundException e){
                    log.error(e.getMessage(),e);
                }
            }
        } catch (IOException e) {
            log.error(e.getMessage(),e);
        }
    }

    /**
     * 删除zip
     */
    public static void deleteZip(File path) {
        if (path.exists()) {
            path.delete();
        }
    }

    /**
     * 删除多个文件方法
     *
     * @param srcfile
     */
    public static void deleteFiles(List<File> srcfile) {
        for (File file : srcfile) {
            if (file.exists()) {
                file.delete();
            }
        }
    }



    /**
     * 获取报告模板的位置
     * @param fileName
     * @return
     */
    public static String getReportTemplateFilePath(String fileName){
        StringBuffer realPath = new StringBuffer("/");
        realPath.append("template");
        realPath.append("/");
        realPath.append("excelResultAndReport");
        realPath.append("/");
        realPath.append(fileName);
        return realPath.toString();
    }

    public static String getStringByFormatAndDate(Date date, String strFormat) {
        String dateStr = "";
        SimpleDateFormat sdf = new SimpleDateFormat(strFormat);
        dateStr = sdf.format(date);
        return dateStr;
    }

    public static String notNull(String param) {
        return param == null ? "" : param.trim();
    }

    public static Date convertStringToDate(String dateString) throws ParseException {
        Date resultDate = null;
        if(StringUtils.isNotBlank(dateString)){
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            dateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
            resultDate = dateFormat.parse(dateString);
        }
        return resultDate;
    }

    /**
     * 判断一个字符串是否是一个数字
     * @param string
     * @return
     */
    public static boolean isNumber(String string){
        if (string.indexOf("E-") != -1){ //如果为true,表示有
            if(string.replace("E-","").matches("^-?\\d+(\\.\\d+)?$")){
                return true;
            }
        }
        Boolean strResult = string.matches("^-?\\d+(\\.\\d+)?$");
        return strResult;
    }

    
    public static void main(String[] args) throws IOException {
		
    	FileInputStream f1 = new FileInputStream(new File("d://file1.xlsx"));
    	FileInputStream f2 = new FileInputStream(new File("d://file2.xlsx"));
    	
    	FileInputStream f3 = new FileInputStream(new File("d://f.txt"));
    	FileInputStream f4 = new FileInputStream(new File("d://f1.txt"));
    	
    	
    	List<FileInputStream> list = new ArrayList<FileInputStream>();
    	list.add(f1);list.add(f2);
    	
    	 XSSFWorkbook workbook1 = new XSSFWorkbook(f1);
    	 XSSFWorkbook workbook2 = new XSSFWorkbook(f2);
    	 
    	Map<String, Workbook> map = new HashMap<String, Workbook>();
    	map.put("file1.xlsx",workbook1);
    	map.put("file2.xlsx",workbook2);
    	
    	Map<String, InputStream> fileMap = new HashMap<String, InputStream>();
    	fileMap.put("f.txt", f3);
    	fileMap.put("f1.txt", f4);
    	
    	String name = "压缩文件";
    	File zipFile = new File("d://压缩文件.rar");
    	
    	zipFiles(map,fileMap,zipFile);
	}
    
    public static void zipFiles(Map<String, Workbook> workbookMap, File zipFile) {
    	zipFiles(workbookMap, null, zipFile);
    }
    
    public static InputStream workbookConvertorStream(Workbook workbook) {
        InputStream in = null;
        try{
            //临时缓冲区
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            //创建临时文件
            workbook.write(out);
            byte [] bookByteAry = out.toByteArray();
            in = new ByteArrayInputStream(bookByteAry);
        }
        catch (Exception e){
        	log.error(e.getMessage(),e);
        }
        return in;
    }
    
    public static void zipFiles(Map<String, Workbook> workbookMap,Map<String,InputStream> fileMap,File zipFile){
        byte[] buf = new byte[1024];
        try (ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile));){
            if(workbookMap != null && workbookMap.size()>0) {
            	Set<String> keys = workbookMap.keySet();
                for(String key:keys){
                    Workbook workbook = workbookMap.get(key);
                    try(InputStream in = workbookConvertorStream(workbook);){
                        out.putNextEntry(new ZipEntry(key));
                        int len;
                        while ((len = in.read(buf)) > 0) {
                            out.write(buf, 0, len);
                        }
                        out.closeEntry();
                    }catch(FileNotFoundException e){
                        log.error(e.getMessage(),e);
                    }
                }
            }
        	
            if(fileMap != null && fileMap.size()>0) {
            	Set<String> files = fileMap.keySet();
                for (String file : files) {
                    InputStream in = fileMap.get(file);
                    out.putNextEntry(new ZipEntry(file));
                    int len;
                    while ((len = in.read(buf)) > 0) {
                        out.write(buf, 0, len);
                    }
                    out.closeEntry();
                    in.close();
                }
            }
        } catch (IOException e) {
            log.error(e.getMessage(),e);
        }

    }
	
}
